package com.cat.binaryTree;

/**
 *   @description https://leetcode.cn/problems/reverse-nodes-in-k-group/
 *   @author 曲大人的喵
 *   @create 2025/9/26 15:52
 *   @since JDK17
 */

public class Solution65 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode virtualNode = new ListNode(0, head), cur, last = virtualNode, pre = null, next;
        int n = 0;
        for (cur = head; cur != null; cur = cur.next) {
            n++;
        }
        cur = head;
        for (; n >= k; n -= k) {
            for (int i = 0; i < k; i++) {
                next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            next = last.next;
            last.next.next = cur;
            last.next = pre;
            last = next;
        }

        return virtualNode.next;
    }
}
